package com.mactivity.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.mactivity.helper.Constants;

/**
 * 
 * @author Shwetha Narayan
 * 
 */
public class LoginFunctions {

	public String userLogin(String emailId, String password) {
		String result = null;

		try {
			ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("emailId", emailId));
			postParameters.add(new BasicNameValuePair("passWord", password));
			String response = null;

			Log.d(Constants.LOG_DATABASE_TAG, "Calling  database");

			// Check if the
			response = CustomHttpClient.executeHttpPost(
					Constants.DATABASE_URL+"Login/login.php",
					postParameters);

			Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved");

			response = response.replaceAll("\n", "");

			if (!response.toString().equalsIgnoreCase("null")) {
				Log.d(Constants.LOG_DATABASE_TAG, "Response from database: "
						+ response);
				result = response;
			} else {
				Log.d(Constants.LOG_DATABASE_TAG,
						"Invalid User name password combination");
			}

		} catch (Exception e) {
			Log.e(Constants.LOGGER_ERROR_TAG,
					"Error in http connection while checking!!" + e.toString());
		}

		return result;
	}

	/**
	 * 
	 * @param response
	 * @return
	 */
	public Map<String, String> getUserDetails(String response) {
		Map<String, String> userDetails = new HashMap<String, String>();

		try {
			JSONArray jArray = new JSONArray(response);
			for (int i = 0; i < jArray.length(); i++) {

				JSONObject json_data = jArray.getJSONObject(i);

				// Get an output to the screen
				userDetails.put(Constants.USER_ID, String.valueOf(json_data
						.getInt(Constants.COLUMN_USER_ID)));
				userDetails.put(Constants.USER_EMAIL_ID,
						json_data.getString(Constants.COLUMN_USER_EMAIL));
				userDetails.put(Constants.USER_NAME,
						json_data.getString(Constants.COLUMN_USER_NAME));

			}
		}

		catch (JSONException e) {
			Log.e(Constants.LOGGER_ERROR_TAG,
					"Error while parsing response data " + e.toString());
		}

		return userDetails;

	}

}
